package com.ymatou.shop.location;

import android.content.Context;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

public class LocationManager {
	
	private static LocationManager sInstance;
	
	private LocationClient mLocationClient;
	
	private LocationManager(Context context) {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");//返回的定位结果包含地址信息
		option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms
		option.disableCache(true);//禁止启用缓存定位
		option.setPoiNumber(0);	//最多返回POI个数
		option.setPoiDistance(1000); //poi查询距离
		option.setPoiExtraInfo(false); //是否需要POI的电话和地址等详细信息
		
		mLocationClient = new LocationClient(context);
		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}
	
	public static LocationManager getInstance(Context context) {
		if(sInstance == null) {
			synchronized (LocationManager.class) {
				if (sInstance == null) {
					sInstance = new LocationManager(context.getApplicationContext());
				}
			}
		}
		return sInstance;
	}
	
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		mLocationClient.stop();
	}
	
	public void getLocation(LocationListener listener) {
		InnerLocationListener innerListener = new InnerLocationListener(listener);
		mLocationClient.registerLocationListener(innerListener);
		mLocationClient.requestLocation();
	}
	
	private class InnerLocationListener implements BDLocationListener {
		
		private LocationListener mListener;
		
		InnerLocationListener(LocationListener listener) {
			mListener = listener;
		}
		
		@Override
		public void onReceivePoi(BDLocation location) {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void onReceiveLocation(BDLocation location) {
			Location loc = null;
			if (location != null) {
				loc = new Location(location.getLatitude(), location.getLongitude(), 
						location.getAddrStr(), location.getCity());
			}
			if (mListener != null) {
				mListener.onReceiveLocation(loc);
			}
			
			mLocationClient.unRegisterLocationListener(this);
		}
	}
}
